package maven.jyhs.com.controller;

import com.alibaba.fastjson2.JSON;
import maven.jyhs.com.dao.ApiResult;
import maven.jyhs.com.entity.Menu;
import maven.jyhs.com.servce.MenuSevrce;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Update;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
public class MenuRestController {
    private static final Logger logger = LogManager.getLogger(MenuRestController.class);

    @Autowired
    private MenuSevrce menuSevrce;

    @GetMapping("/menu")
    public String getMenuList() {
        System.out.println("查询菜单");
        return JSON.toJSONString(menuSevrce.getMenuList());
    }

    @GetMapping("/menu/{id}")
    public String getMenuById(@PathVariable("id") Integer id) {
        System.out.println("查询菜单" + id);
        return "menu";
    }

    @PostMapping("/menu")
    public ApiResult addMenu(@Valid @RequestBody Menu menu, BindingResult bindingResult, HttpSession session) {

        System.out.println("新增菜单" + menu);
        return new ApiResult(200, "新增成功", menuSevrce.addMenu(menu));
    }

    @PutMapping("/menu/{id}")
    public ApiResult updateMenu(@Valid @PathVariable("id") Integer id, @RequestBody Menu menu) {
        System.out.println("更新菜单" + menu);

        return new ApiResult(200, "更新成功", menuSevrce.updateMenu(menu));
    }

    @PutMapping("/menu4")
    public boolean updateMenu4(@RequestBody Menu menu) {

        System.out.println("更新菜单" + menu);
        return true;
    }

    @PostMapping("/menu/updateImage")
    public ApiResult updateMenuImage(List<MultipartFile> files) throws IOException {
        List<String> fileUrls = new ArrayList<>();


            for (MultipartFile file : files) {
                String newFileName = System.currentTimeMillis() + "_" + file.getOriginalFilename();
                file.transferTo(new File("D:/image/" + newFileName));
                fileUrls.add("http://localhost:8080/image/" + newFileName);
            }
            return new ApiResult(200, "上传成功", fileUrls);

    }
    @DeleteMapping("/menu/{id}")
    public int deleteMenu(@PathVariable("id") Integer id) {
        System.out.println("删除菜单" + id);
        return menuSevrce.deleteMenu(id);
    }


}
